#ifndef SCT_MEDIACENTER_MEDIACENTER_H
#define SCT_MEDIACENTER_MEDIACENTER_H

#include <microhttpd.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>

#include "rtpsession.h"
#include "rtpudpv4transmitter.h"
#include "rtpipv4address.h"
#include "rtpsessionparams.h"
#include "rtperrors.h"
#include "rtppacket.h"

#include "sct/core/common.h"
#include "sct/core/thread.h"
#include "sct/core/mutex.h"
#include "sct/core/hash.h"

#include "sct/framework/object.h"

#include "sct/rtspserver/rtspserverinterface.h"

using namespace jrtplib;
namespace sct
{
class CMediaCenter: public CThreadCallBack, public CObject
{
public:
	CMediaCenter(const char * conf);
	virtual ~CMediaCenter();

protected:
	virtual int main(CThread * caller);
	virtual void onTimerTimeout(const int id);

private:
	enum State
	{
		Initing = SCT_ENUM_OFFSET,
		Running,
		Terminated,
	};

	class CRTSPSessionInfo
	{
	public:
		CServerMediaSession * media_session;
		CServerMediaSubsession * media_subsession;
		bool in_use;

		double last_update_time;
	};

	class CActiveItem
	{
	public:
		std::string machine;
		std::string stream_major;
		std::string stream_minor;

		uint32_t key;

		CRTSPSessionInfo * rtsp_info;

		std::ofstream file;

		double last_update_time;
	};

	enum ConstValue
	{
		RtspServerMediaSessionSize = 10,
	};

private:
	void recvloop();
	static int
	accessHandlerCallback (void *cls,
	struct MHD_Connection *connection,
	const char *url,
	const char *method,
	const char *version,
	const char *upload_data, size_t *upload_data_size, void **ptr);

	uint32_t createStoragePoint(const char * mac, const char * major, const char * minor);
	uint32_t createStreamforwardPoint(const char * mac, const char* major);
	CRTSPSessionInfo* findFreeRtspSession();
	const char* getStreamUrlById(const uint32_t id);

	/**
	 * @return 0 mean success
	 */
	int onHttpGetMethon(const char * url, xmlNodePtr node);

	/**
	 * @return 0 mean success
	 */
	int onHttpPostMethon(const char * url, xmlDocPtr doc);

	void updateActiveItems();
private:
	RTPSession * mSess;

	State mState;
	CThread * mRecvThd;

	CRTSPServerInterface * mRtspServer;
	CRTSPSessionInfo* mServerSessions[RtspServerMediaSessionSize];

	struct MHD_Daemon * mHttpServ;

	CMutex * mMutex;
	std::list<CActiveItem*> mActiveItems;
	CHash * mHashItems;

	std::string mConfFilePath;
	std::string mMainIp;
	int mHttpPort;
	int mRtpPort;
	int mRtspPort;
	std::string mFileStoragePath;

	int mTimerBootup;
	int mTimerPeriod;

	int mTimeoutValue;
};
}
#endif
